/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistence;

import entityBeans.Dataset;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entityBeans.Recordlevelelement;
import java.util.ArrayList;
import java.util.List;
import persistence.exceptions.NonexistentEntityException;

/**
 *
 * @author allankv
 */
public class DatasetJpaController {

    public DatasetJpaController() {
        emf = Persistence.createEntityManagerFactory("bdd-javaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public Dataset save(Dataset dataset) {
        Dataset aux = findDataset(dataset.getDataset());
        if(aux==null)
            return create(dataset);
        else
            return aux;
    }

    public Dataset create(Dataset dataset) {
        Dataset r =null;
        if (dataset.getRecordlevelelementList() == null) {
            dataset.setRecordlevelelementList(new ArrayList<Recordlevelelement>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Recordlevelelement> attachedRecordlevelelementList = new ArrayList<Recordlevelelement>();
            for (Recordlevelelement recordlevelelementListRecordlevelelementToAttach : dataset.getRecordlevelelementList()) {
                recordlevelelementListRecordlevelelementToAttach = em.getReference(recordlevelelementListRecordlevelelementToAttach.getClass(), recordlevelelementListRecordlevelelementToAttach.getIdrecordlevelelement());
                attachedRecordlevelelementList.add(recordlevelelementListRecordlevelelementToAttach);
            }
            dataset.setRecordlevelelementList(attachedRecordlevelelementList);
            r = em.merge(dataset);
            for (Recordlevelelement recordlevelelementListRecordlevelelement : dataset.getRecordlevelelementList()) {
                Dataset oldDatasetOfRecordlevelelementListRecordlevelelement = recordlevelelementListRecordlevelelement.getDataset();
                recordlevelelementListRecordlevelelement.setDataset(dataset);
                recordlevelelementListRecordlevelelement = em.merge(recordlevelelementListRecordlevelelement);
                if (oldDatasetOfRecordlevelelementListRecordlevelelement != null) {
                    oldDatasetOfRecordlevelelementListRecordlevelelement.getRecordlevelelementList().remove(recordlevelelementListRecordlevelelement);
                    oldDatasetOfRecordlevelelementListRecordlevelelement = em.merge(oldDatasetOfRecordlevelelementListRecordlevelelement);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return r;
    }

    public void edit(Dataset dataset) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Dataset persistentDataset = em.find(Dataset.class, dataset.getIddataset());
            List<Recordlevelelement> recordlevelelementListOld = persistentDataset.getRecordlevelelementList();
            List<Recordlevelelement> recordlevelelementListNew = dataset.getRecordlevelelementList();
            List<Recordlevelelement> attachedRecordlevelelementListNew = new ArrayList<Recordlevelelement>();
            for (Recordlevelelement recordlevelelementListNewRecordlevelelementToAttach : recordlevelelementListNew) {
                recordlevelelementListNewRecordlevelelementToAttach = em.getReference(recordlevelelementListNewRecordlevelelementToAttach.getClass(), recordlevelelementListNewRecordlevelelementToAttach.getIdrecordlevelelement());
                attachedRecordlevelelementListNew.add(recordlevelelementListNewRecordlevelelementToAttach);
            }
            recordlevelelementListNew = attachedRecordlevelelementListNew;
            dataset.setRecordlevelelementList(recordlevelelementListNew);
            dataset = em.merge(dataset);
            for (Recordlevelelement recordlevelelementListOldRecordlevelelement : recordlevelelementListOld) {
                if (!recordlevelelementListNew.contains(recordlevelelementListOldRecordlevelelement)) {
                    recordlevelelementListOldRecordlevelelement.setDataset(null);
                    recordlevelelementListOldRecordlevelelement = em.merge(recordlevelelementListOldRecordlevelelement);
                }
            }
            for (Recordlevelelement recordlevelelementListNewRecordlevelelement : recordlevelelementListNew) {
                if (!recordlevelelementListOld.contains(recordlevelelementListNewRecordlevelelement)) {
                    Dataset oldDatasetOfRecordlevelelementListNewRecordlevelelement = recordlevelelementListNewRecordlevelelement.getDataset();
                    recordlevelelementListNewRecordlevelelement.setDataset(dataset);
                    recordlevelelementListNewRecordlevelelement = em.merge(recordlevelelementListNewRecordlevelelement);
                    if (oldDatasetOfRecordlevelelementListNewRecordlevelelement != null && !oldDatasetOfRecordlevelelementListNewRecordlevelelement.equals(dataset)) {
                        oldDatasetOfRecordlevelelementListNewRecordlevelelement.getRecordlevelelementList().remove(recordlevelelementListNewRecordlevelelement);
                        oldDatasetOfRecordlevelelementListNewRecordlevelelement = em.merge(oldDatasetOfRecordlevelelementListNewRecordlevelelement);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = dataset.getIddataset();
                if (findDataset(id) == null) {
                    throw new NonexistentEntityException("The dataset with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Dataset dataset;
            try {
                dataset = em.getReference(Dataset.class, id);
                dataset.getIddataset();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The dataset with id " + id + " no longer exists.", enfe);
            }
            List<Recordlevelelement> recordlevelelementList = dataset.getRecordlevelelementList();
            for (Recordlevelelement recordlevelelementListRecordlevelelement : recordlevelelementList) {
                recordlevelelementListRecordlevelelement.setDataset(null);
                recordlevelelementListRecordlevelelement = em.merge(recordlevelelementListRecordlevelelement);
            }
            em.remove(dataset);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Dataset> findDatasetEntities() {
        return findDatasetEntities(true, -1, -1);
    }

    public List<Dataset> findDatasetEntities(int maxResults, int firstResult) {
        return findDatasetEntities(false, maxResults, firstResult);
    }

    private List<Dataset> findDatasetEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Dataset.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Dataset findDataset(String q) {
        Query query= getEntityManager().createNamedQuery("Dataset.findByDataset");
        query.setParameter("dataset",q);

        return query.getResultList().isEmpty()?null:(Dataset)query.getResultList().get(0);
    }
    public Dataset findDataset(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Dataset.class, id);
        } finally {
            em.close();
        }
    }

    public int getDatasetCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Dataset> rt = cq.from(Dataset.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
